package com.rejia.jldemo.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.rejia.jldemo.common.RequestData;
import com.rejia.jldemo.common.ResponseData;
import com.rejia.jldemo.service.vo.CaptureInfo;
import com.rejia.jldemo.service.vo.DataContent;
import com.rejia.jldemo.service.vo.FaceInfo;
import com.rejia.jldemo.utils.Imagebase64;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Type;

/**
 * @author guofei
 * @date 2020/3/30 11:21
 */
@Slf4j
@RestController
@RequestMapping(value = "camera/receive/v1")
public class ReceiveController {

    @Value("${capture.path}")
    private String basePath;

    /**
     * 接收抓拍数据
     *
     * @param obj 抓拍数据
     * @return
     */
    @RequestMapping("/captureInfo/test")
    public ResponseData receiveDataTest(@RequestBody Object obj) {

        log.debug("captureInfo data : {}", JSON.toJSONString(obj));
        String name = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmssSSS");
        Type type = new TypeReference<RequestData<DataContent>>() {
        }.getType();
        RequestData<DataContent> requestData = JSON.parseObject(JSON.toJSONString(obj), type);
        DataContent data = requestData.getData();
        CaptureInfo captureInfo = data.getCaptureInfo();
        FaceInfo faceInfo = data.getFaceInfo();
        log.debug("faceInfo is {}", JSON.toJSONString(faceInfo));
        String backgroundPicture = captureInfo.getBackgroundPicture();
        if (StringUtils.isNotEmpty(backgroundPicture)) {
            Imagebase64.base64StringToImage(backgroundPicture, basePath + "backgroundPicture_" + name + ".jpg");
        }
        String bodyPicture = captureInfo.getBodyPicture();
        if (StringUtils.isNotEmpty(bodyPicture)) {
            Imagebase64.base64StringToImage(bodyPicture, basePath + "bodyPicture_" + name + ".jpg");
        }
        String facePicture = captureInfo.getFacePicture();
        if (StringUtils.isNotEmpty(facePicture)) {
            Imagebase64.base64StringToImage(facePicture, basePath + "facePicture_" + name + ".jpg");
        }

        return responseResultData("captureInfoResponse", data.getDeviceInfo().getDeviceId());
    }


    private ResponseData responseResultData(String resultResponse, String deviceUuid) {
        ResponseData<Object> responseData = new ResponseData<>();
        responseData.setCode(1);
        responseData.setName(resultResponse);
        Long timeStamp = System.currentTimeMillis() / 1000;
        responseData.setTimeStamp(timeStamp);
        responseData.setSession(deviceUuid + "_" + timeStamp);
        return responseData;
    }

}
